﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FilStartUps_Mobile.Models;
using System.Data.SqlTypes;
using System.Data;

namespace FilStartUps_Mobile.Helpers
{
    public class Session_Helper
    {
        FilStartUpsEntities db_connect = new FilStartUpsEntities();
        public void CreateSession(int memberid)
        {

            Session session = new Session();
            session.memberidFK = memberid;
            session.session_flag = true;
            session.sessiondatelogon = DateTime.Now;
            session.sessiondatelogout = Convert.ToDateTime(SqlDateTime.MinValue.Value);
            db_connect.Sessions.Add(session);
            db_connect.SaveChanges();


        }

        public void AbandonSession(string email)
        {

            var member = db_connect.Members.Where(m => m.emailaddress == email.Trim()).SingleOrDefault();
            var sessionlog = db_connect.Sessions.Where(s => s.memberidFK == member.memberidPK && s.session_flag == true).SingleOrDefault();
            sessionlog.sessiondatelogout = DateTime.Now;
            sessionlog.session_flag = false;
            db_connect.Entry(sessionlog).State = EntityState.Modified;
            db_connect.SaveChanges();

        }
        public bool CheckSession(int memberid)
        {
            var session = db_connect.Sessions.Where(s => s.memberidFK.Equals(memberid)
                                                             && s.session_flag.Equals(true)).SingleOrDefault();
            //true => Existing Session
            if (session != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public void UpdateSession(int memberid)
        {
            var updatesession = db_connect.Sessions.Where(s => s.memberidFK.Equals(memberid)
                                                && s.session_flag.Equals(true)).SingleOrDefault();
            updatesession.sessiondatelogon = DateTime.Now;
            db_connect.Entry(updatesession).State = EntityState.Modified;
            db_connect.SaveChanges();
        }
    }
}